package com.dang.alex.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dang.alex.model.User;
import com.dang.alex.service.imp.UserServiceImp;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({ "/LoginServlet", "/user/Login.do" })
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	public static final String METHOD_TOLOGIN="0";
	public static final String METHOD_LOGIN="1";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		
	}

	
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String  method=req.getParameter("method");
    	if(method!=null){
    		switch(method){
    		case LoginServlet.METHOD_TOLOGIN:
    			req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
    			break;
    		case LoginServlet.METHOD_LOGIN:
    			try {
					Login(req, resp);
				} catch (Exception e) {
					e.printStackTrace();
				}
    			
    			break;
    		default :
    			break;
    		}
    	}
    }


	private void Login(HttpServletRequest req, HttpServletResponse resp) {
		String email=req.getParameter("email");
		String password=req.getParameter("password");
		UserServiceImp us=new UserServiceImp();
		try {
			User u=us.findByEmail(email);
			if(u==null||!password.equals(u.getPassword())){
				req.setAttribute("login_err", "用户名或密码错误");
				req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
				return ;
			}
			u.setLast_login_ip(req.getRemoteAddr());
			u.setLast_login_time(System.currentTimeMillis());
			us.update(u);
			
			req.getSession().setAttribute("s_user", u);
			
			if(!u.isIs_email_verify()){
				req.getRequestDispatcher("/WEB-INF/view/user/login_form.jsp").forward(req, resp);
				return;
			}
			//req.getRequestDispatcher("/WEB-INF/view/home/main.jsp").forward(req, resp);
			resp.sendRedirect(req.getContextPath()+"/main.do");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	
}
